﻿using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Fluid;
using Fluid.Ast;

namespace ZYing.LiquidThemeEngine.Ast;

public class SectionStatement : Statement
{
    public SectionStatement(Expression name)
    {
        Name = name;
    }

    public Expression Name { get; }


    public override async ValueTask<Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext ctx)
    {
        var value = await Name.EvaluateAsync(ctx);
        if (value.IsNil())
        {
            return Completion.Normal;
        }

        var id = value.ToStringValue();
        if (string.IsNullOrWhiteSpace(id))
        {
            return Completion.Normal;
        }

        var context = (LiquidThemeTemplateContext)ctx;
        var settings = await context.GetThemeSettingAsync();
        await context.RenderSectionAsync(writer, settings, id, false);
        return Completion.Normal;
    }
}